package org.jadelyre.core.task;


import org.jadelyre.core.Channel;
import org.jadelyre.core.codec.Packet;
import org.jadelyre.core.codec.sun.SunPacket;
import org.jadelyre.core.exception.CodecException;
import org.jadelyre.core.worker.Worker;
import org.jadelyre.utils.ByteBufferUtils;

import java.nio.ByteBuffer;

public class DecodeTask extends ChannelTask<ByteBuffer> {

    private ByteBuffer lastByteBuffer = null;

    public DecodeTask(Channel channel, Worker<ByteBuffer> worker) {
        super(channel, worker);
//        executor = channel.getJadeLyre().getWorkerFactory().getDecodeWorker();
    }

    @Override
    protected <T> void work(T t) throws CodecException {
        ByteBuffer byteBuffer = (ByteBuffer) t;
        if (null != lastByteBuffer) {
            byteBuffer = ByteBufferUtils.splice(lastByteBuffer, byteBuffer);
            lastByteBuffer = null;
        }
        byteBuffer.order(SunPacket.BYTE_ORDER);
        byteBuffer.mark();
        while(true){
            Packet packet;
            try {
                packet = channel.getJadeLyre().getCodec().decode(byteBuffer);
            } catch (CodecException e) {
                //解析出错，丢弃包和上次的包
                lastByteBuffer = null;
                throw e;
            }
            if (null == packet) {
                //长度不够,半包处理
                byteBuffer.reset();
                lastByteBuffer = byteBuffer;
                break;
            }
//            channel.getHandleTask().addTask(packet).execute();
            channel.getHandleWorker().work(packet);
            if (byteBuffer.hasRemaining()) {
                //粘包处理
                continue;
            }
            lastByteBuffer = null;
            break;
        }
    }

}
